package cn.wolfcode.mq;

import cn.wolfcode.ws.WebSocketServer;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.concurrent.TimeUnit;

@Component
@RocketMQMessageListener(consumerGroup = "websocketGroup",topic = MQConstants.ORDER_RESULT_TOPIC)
public class OrderResultListener implements RocketMQListener<OrderMQResult> {
    // 监听 OrderPeddingQueueListener 发出的下单成功的消息,响应回浏览器
    @Override
    public void onMessage(OrderMQResult msg) {
        String token = msg.getToken();
        int count = 0;
        try{
            do {
                Session session = WebSocketServer.clients.get(token);
                if (session != null) {
                    session.getBasicRemote().sendText(JSON.toJSONString(msg));
                    return;
                }
                // 可能创建消息消费已经完成 webSocket 与浏览器之间的连接通道还没建立完成
                TimeUnit.MILLISECONDS.sleep(100);
                count++;
            }while (count < 3);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
